package com.example.kafkademo.consumer;

import com.example.kafkademo.util.CosUtil;
import com.example.kafkademo.util.PdfUtil;
import com.example.kafkademo.util.PebbleUtil;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.kafka.client.consumer.KafkaConsumer;
import io.vertx.kafka.client.serialization.JsonObjectDeserializer;
import org.apache.kafka.common.serialization.LongDeserializer;

import java.io.File;
import java.util.Properties;

public class VppcConsumer {

    private static String PDFPATH = "src/main/resources/pdf/";

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        final Properties props = new Properties();
        props.put("bootstrap.servers", "192.168.1.14:9092");
        props.put("group.id", "GroupA");
        props.put("key.deserializer", LongDeserializer.class.getName());
        props.put("value.deserializer", JsonObjectDeserializer.class.getName());

        KafkaConsumer<Long, JsonObject> consumer = KafkaConsumer.create(vertx, props);

        consumer.subscribe("vppc").handler(ar -> {
            JsonObject record = ar.value();
            String templateName = record.getString("templateName");

            try {
                PebbleUtil.render(vertx, templateName, record, res -> {
                    String html = res.result();

                    String pdfName = record.getString("pdfName");
                    String pdfPath = PDFPATH + pdfName;
                    PdfUtil.covert(html, pdfPath);

                    CosUtil.upload(vertx, pdfPath, v -> {
                        String cosPdfPath = v.result();

                        //删除本地生成的pdf文件
                        File file = new File(pdfPath);
                        file.delete();

                        System.out.println("cos上的文件路径" + cosPdfPath);
                        vertx.close();
                    });
                    
                    System.out.println("hello");
                    //删除本地生成的pdf文件
                    File file = new File(pdfPath);
                    file.delete();
                });

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        });
    }
}
